using System;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.UI;

namespace EntityKit.Runtime
{
    public class RawImageLocalizationAsync : MonoBehaviour
    {
        [Tooltip("本地化图片的键值")] [SerializeField] private string LocalizationID;

        [Tooltip("是否设置本地化图片的宽高为原生宽高")] public bool SetNativeSize = true;

        [Tooltip("是否初始化刷新")] [SerializeField] private bool InitRefresh = true;

        private RawImage m_Image;

        private void Awake()
        {
            m_Image = GetComponent<RawImage>();
        }

        private void Start()
        {
            EventKit.AddListener<EventLocalizationLanguageChanged>(OnLocalizationLanguageChanged);
            if (InitRefresh)
            {
                _ = RefreshSafe();
            }
        }

        private void OnDestroy()
        {
            EventKit.RemoveListener<EventLocalizationLanguageChanged>(OnLocalizationLanguageChanged);
        }

        private void OnLocalizationLanguageChanged(IEventMessage obj)
        {
            _ = RefreshSafe();
        }

        private async Task RefreshSafe()
        {
            try
            {
                if (string.IsNullOrEmpty(LocalizationID))
                {
                    return;
                }

                var texture = await LocalizationKit.GetImageAsset2TextureAsync(LocalizationID, this.GetGameObjectDestroyToken());
                
                if (m_Image == null)
                {
                    m_Image = GetComponent<RawImage>();
                }
                
                if (m_Image != null)
                {
                    m_Image.texture = texture;
                    if (SetNativeSize)
                        m_Image.SetNativeSize();
                }
            }
            catch (Exception ex)
            {
                Debug.LogError($"Error refreshing sprite: {ex.Message}", this);
            }
        }

        public void SetLocalizationID(string id)
        {
            LocalizationID = id;
            _ = RefreshSafe();
        }
    }
}